<template>
    <div class="md-ckeditor">
        <div :ref="id"></div>
        <el-dialog title="上传文件"
                   :append-to-body="true"
                   :visible.sync="upload.show"
                   :close-on-click-modal="false">
            <file-upload :insert="upload.insert" @close="upload.show=false"/>
        </el-dialog>
    </div>
</template>

<script>
    import editor from "./ckeditor";
    import "./translations/zh-cn"
    import fileUpload from "./upload";

    export default {
        data() {
            return {
                editor: null,
                set: true,
                upload: {},
            }
        },
        components: {fileUpload},
        props: {
            'value': {
                default: ''
            }
            , 'id': {
                type: String
                , default: 'ckeditor'
            }
        },
        model: {
            prop: 'value'
        },
        watch: {
            'value': function () {
                if (this.value.length > 0 && this.set) {
                    this.set = false;
                    this.editor.setData(this.value);
                }
            }
        },
        mounted() {
            editor.create(this.$refs[this.id], {
                language: 'zh-cn',
                media: {
                    click: callback => {
                        this.upload = {
                            insert: callback,
                            show: true,
                        };
                    }
                },
                table: {
                    contentToolbar: [
                        'tableColumn',
                        'tableRow',
                        'mergeTableCells'
                    ]
                },
            }).then(editor => {
                this.editor = editor;
                // 获取编辑器内容
                // 实时获取
                editor.model.document.on('change', () => {
                    this.$emit('input', editor.getData())
                });
                // 编辑器失去光标时获取
                // editor.editing.view.document.on('blur', () => {
                //     this.set = false;
                //     this.$emit('input', editor.getData())
                // })
            }).catch(error => {
                console.error(error);
            });
        },
        beforeDestroy() {
            this.editor.destroy()
        }
    }
</script>
